﻿using MediatR;
using Microsoft.AspNetCore.SignalR;
using Microsoft.Extensions.Logging;
using ORS.OrderRobot.Service.Helper;
using ORS.OrderRobot.ServiceContracts;
using ORS.OrderRobot.ServiceContracts.Dtos;

namespace ORS.OrderRobot.Service.EventHandler
{
    /// <summary>
    /// 订购商品的事件处理程序
    /// </summary>
	public class PurchaseHandler : INotificationHandler<PurchaseEvent>
    {
        private readonly ILogger<PurchaseHandler> _logger;
        private readonly IShoppingService _shoppingService;
        private readonly IHubContext<MessageHub> _hubContext;
        private readonly IAccountLoginService _accountLoginService;
        private readonly ISystemConfigService _systemConfigService;
        private readonly string _msgObj = "商品订购";
        public PurchaseHandler(
            ILogger<PurchaseHandler> logger,
            IShoppingService shoppingService,
            IHubContext<MessageHub> hubContext,
            IAccountLoginService accountLoginService,
            ISystemConfigService systemConfigService
        )
        {
            _logger = logger;
            _shoppingService = shoppingService;
            _hubContext = hubContext;
            _accountLoginService = accountLoginService;
            _systemConfigService = systemConfigService;
        }

        public async Task Handle(PurchaseEvent notification, CancellationToken cancellationToken)
        {
            var userList = await _accountLoginService.GetLoginedAccounts();
            if (notification.excludeEmail!=null && notification.excludeEmail.Any())
            {
                //筛选出不在notification.excludeEmail中的
                userList = userList?.Where(ul => !notification.excludeEmail.Contains(ul)).ToList();
            }
            if (userList == null || !userList.Any())
            {
                await MsgHelper.SendAsync(_hubContext, new MsgData { Obj = _msgObj, Action = "没有已登录的用户", Type = Consts.ErrMsg });
                _logger.LogWarning("没有已登录的用户");
                return;
            }
            var systemConfig = await _systemConfigService.GetConfigAsync();
            try
            {
                var tasks = userList.Select(async email =>
                {
                    var input = new ShoppingInput(){
                        Email = email,
                        ProductName = notification.productName,
                        Cart = new(){
                        new() {
                            product_id = notification.ProductId,
                            quantity = 1
                        }
                    }};
                    await MsgHelper.SendAsync(_hubContext, new MsgData { Obj = _msgObj, Action = $"{email}开始订购" });
                    await _shoppingService.ShoppingAsync(input);
                });
                await Task.WhenAll(tasks);
            }
            catch { }

        }
    }
}

